package com.lw.acl.controller;

import com.lw.acl.entity.User;
import com.lw.commonutil.result.Result;
import com.lw.commonutil.result.ResultCodeEnum;
import com.lw.servicebase.exception.GuliException;
import com.lw.servicebase.profile.ProfileResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.xmlbeans.impl.xb.xsdschema.Attribute;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin/acl/user")
public class UserController {
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        String username = user.getUsername();
        String password = user.getPassword();
        UsernamePasswordToken token = new UsernamePasswordToken( username, password );
        //2.获取subject
        Subject subject = SecurityUtils.getSubject();
        //3.调用login方法 捕获异常
        subject.login( token );
        //4.获取sessionId
        String sessionId = (String) subject.getSession().getId();
        //4.返回sessionId
        return Result.ok( sessionId );
    }
    //获取用户信息
    @GetMapping("/profile")
    public Result profile(){
        //获取安全数据
        Subject subject=SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();
        ProfileResult result = (ProfileResult) principals.getPrimaryPrincipal();
        return Result.ok( result );
    }
    //清除session
    @GetMapping("/logout")
    public Result logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.getSession().stop();
        return Result.ok();
    }
    //shiro过滤后请求链接
    @GetMapping("/authError")
    public Result authError(@RequestParam("code") Integer code){
        if (code==1){
            throw new GuliException( ResultCodeEnum.LOGIN_AUTH );
        }else {
            throw new GuliException( ResultCodeEnum.LOGIN_ACL );
        }
    }
}
